package com.api.user.service.impl;

import com.api.user.dao.GameProfileMapper;
import com.api.user.dao.TeamMapper;
import com.api.user.dao.TeamUserMapper;
import com.api.user.dao.UserFriendMapper;
import com.api.user.model.GameProfile;
import com.api.user.model.Team;
import com.api.user.model.TeamUser;
import com.api.user.model.UserFriend;
import com.api.user.service.TeamUserService;
import com.api.core.service.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.api.common.JSONUtils;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * Created by wanghuiwen on 2021/03/27.
 */
@Service
@Transactional
public class TeamUserServiceImpl extends AbstractService<TeamUser> implements TeamUserService {
    @Resource
    private TeamUserMapper teamUserMapper;
    @Resource
    private UserFriendMapper userFriendMapper ;
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private GameProfileMapper gameProfileMapper;

    @Override
    public Result list(String search, String order, Integer page, Integer size){
        Map<String, Object> params = JSONUtils.json2map(search);
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
                if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
                if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
            }
        PageHelper.startPage(page, size);
        List<Map<String, Object>> res = teamUserMapper.list(params, orderParams);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Result applications(Long teamId, String order, Integer page, Integer size) {
        Map<String, Object> params = new HashMap<>();
        params.put("teamId",teamId);
        params.put("type","apply");
        params.put("agree","1");
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
            if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
            if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
        }
        PageHelper.startPage(page, size);
        List<Map<String, Object>> res = teamUserMapper.list(params, orderParams);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Result users(Long teamId, String order, Integer page, Integer size) {
        Map<String, Object> params = new HashMap<>();
        params.put("teamId",teamId);
        params.put("agree",2);

        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
            if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
            if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
        }
//        PageHelper.startPage(page, size);
        List<Map<String, Object>> res = teamUserMapper.list(params, orderParams);
//        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        Map<String,Object> result = new HashMap<>();
        result.put("usrs",res);
        return ResultGenerator.genSuccessResult(result);
    }


    @Override
    public TeamUser getByTeamIdAndUserId(Long teamId, Long userId) {
        return teamUserMapper.getByTeamIdAndUserId(teamId,userId);
    }

    @Override
    public Result invite(Long teamId, String userIds) {

        String [] userids = userIds.split(",");
        for (int i=0;i<userids.length;i++){
            TeamUser teamUser = this.getByTeamIdAndUserId(teamId,Long.parseLong(userids[i]));
            if(teamUser != null){
                if(teamUser.getAgree() == 1) return ResultGenerator.genFailResult(400,"Include users who have been invited");
                if(teamUser.getAgree() == 3) return ResultGenerator.genFailResult(400,"Include users who have been rejected");
                return ResultGenerator.genFailResult(400,"Include users who have been invited");
            }
            teamUser = new TeamUser();
            teamUser.setTeamId(teamId);
            teamUser.setUserId(Long.parseLong(userids[i]));
            teamUser.setCreateTime(new Date().getTime());
            teamUser.setType("invite");
            teamUser.setAgree(1);
            this.save(teamUser);
        }
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result moveOut(Long teamId, String userIds) {
        String [] userids = userIds.split(",");
        for (int i=0;i<userids.length;i++){
            TeamUser teamUser = this.getByTeamIdAndUserId(teamId,Long.parseLong(userids[i]));
            if(teamUser != null){

                teamUserMapper.deleteNew(teamUser);
            }

        }
        return ResultGenerator.genSuccessResult();

    }

    @Override
    public Result join(Long teamId, Long userId) {
        List<GameProfile> profiles = gameProfileMapper.findByUserId(userId);
        if(profiles==null || profiles.size()<1){
            return  ResultGenerator.genFailResult(400,"first add game Profile");
        }
        //todo 判断是否是好友
        Team team = teamMapper.selectByPrimaryKey(teamId);
        //判断A和B是不是朋友关系
        UserFriend userFriend = userFriendMapper.getFriend(userId,team.getLeaderId());
        if(userFriend==null){
            return ResultGenerator.genFailResult(400,"Please add friend first");
        }
        TeamUser teamUser = this.getByTeamIdAndUserId(teamId,userId);
        if(teamUser != null){
            if (teamUser.getAgree() == 1) {
                return ResultGenerator.genFailResult(400, teamUser.getType().equals("invite") ? "Already invited" : "Already applied");
            }
            if (teamUser.getAgree() == 2) {
                return ResultGenerator.genFailResult(400,"Has been a team member");
            }
            if (teamUser.getAgree() == 3) {
                return ResultGenerator.genFailResult(400,"Rejected to join this team");
            }
        }
        teamUser = new TeamUser();
        teamUser.setTeamId(teamId);
        teamUser.setUserId(userId);
        teamUser.setCreateTime(new Date().getTime());
        teamUser.setType("apply");
        teamUser.setAgree(1);
        this.save(teamUser);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result decision(TeamUser teamUser) {
        TeamUser teamUser1 = this.getByTeamIdAndUserId(teamUser.getTeamId(),teamUser.getUserId());
        teamUser1.setAgree(teamUser.getAgree());
        if(teamUser.getAgree() == 2){
            teamUser1.setJoinedTime(new Date().getTime());
        }
        teamUserMapper.updateNew(teamUser1);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public List<Map<String, Object>> getByUserId(Long userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId",userId);
        List<Map<String, Object>> res = teamUserMapper.list(params, new HashMap<String, Object>());
        return res;
    }
}
